package org.springblade.aop.impl;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springblade.common.tool.DateTime;
import org.springblade.common.tool.ThreadPoolUtils;
import org.springblade.core.tool.utils.SpringUtil;
import org.springblade.entity.TimedTaskHistory;
import org.springblade.service.ITimedTaskHistoryService;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.CompletableFuture;

/**
 * 定时任务线程切面处理
 * @author 李家民
 */
@Component
@Aspect
public class TaskThreadHandleImpl {

	/**
	 * 异步线程池处理 防止因为线程卡顿
	 * @param point
	 * @return
	 * @throws Throwable
	 */
	@Around("@annotation(org.springblade.aop.TaskThreadHandle)")
	public Object asyncThreadExecute(ProceedingJoinPoint point) throws Throwable {
		CompletableFuture.runAsync(() -> {
			Date startDate = new Date();
			Signature signature = point.getSignature();
			String methodName = signature.getName();
			int status = 0;
			String description = "";
			try {
				point.proceed();

				// 这里应该套一层超时 以后再说
				// ...

			} catch (Throwable e) {
				status = 1;
				description = e.getMessage();
				e.printStackTrace();
			}
			Date endDate = new Date();
			String computationTime = DateTime.computationTime(startDate, endDate);

			// save db
			try {
				TimedTaskHistory timedTaskHistory = new TimedTaskHistory(methodName,
					DateTime.simpleDateFormat.format(startDate),
					DateTime.simpleDateFormat.format(endDate),
					computationTime, status, description
				);
				SpringUtil.getBean(ITimedTaskHistoryService.class).save(timedTaskHistory);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}, ThreadPoolUtils.getThreadPool());

		// 不要返回值了
		return null;
	}
}
